package com.zym.init.controller.backend;

import com.zym.init.core.annotation.ApiBackendRestController;
import com.zym.init.core.annotation.Log;
import com.zym.init.core.controller.BaseController;
import com.zym.init.core.domain.AjaxResult;
import com.zym.init.core.exception.ServiceException;
import com.zym.init.model.query.PermissionQuery;
import com.zym.init.service.PermissionService;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;
import java.util.List;

import static com.zym.init.core.constant.CommonConstant.FORBIDDEN_DELETE_PERMISSION_IDS;

@Validated
@ApiBackendRestController
@RequestMapping(path = "/permission", produces = "application/json")
public class PermissionController extends BaseController {

    final private PermissionService permissionService;

    public PermissionController(PermissionService permissionService) {
        this.permissionService = permissionService;
    }

    /**
     * 获取权限列表
     */
    @Log(title = "获取权限列表")
    @PreAuthorize("@ss.hasPermission('system:permission:list')")
    @GetMapping
    public AjaxResult list(PermissionQuery query) {
        return success("获取成功", permissionService.getPage(query));
    }

    /**
     * 新增权限
     */
    @Log(title = "新增权限")
    @PreAuthorize("@ss.hasPermission('system:permission:add')")
    @PostMapping
    public AjaxResult add(@RequestBody @Validated(value = {PermissionQuery.Add.class}) PermissionQuery query) {
        return permissionService.add(query) ? success("新增成功") : fail("新增失败");
    }

    /**
     * 编辑权限
     */
    @Log(title = "编辑权限")
    @PreAuthorize("@ss.hasPermission('system:permission:edit')")
    @PutMapping
    public AjaxResult edit(@RequestBody @Validated(value = {PermissionQuery.Update.class}) PermissionQuery query) {
        if (Arrays.stream(FORBIDDEN_DELETE_PERMISSION_IDS).toList().contains(query.getPermissionId())) {
            throw new ServiceException("不能编辑系统默认权限");
        }
        return permissionService.edit(query) ? success("编辑成功") : fail("编辑失败");
    }

    /**
     * 删除权限
     */
    @Log(title = "删除权限")
    @PreAuthorize("@ss.hasPermission('system:permission:delete')")
    @DeleteMapping
    public AjaxResult delete(@RequestParam("ids") List<Long> ids) {
        for (Long forbiddenDeletePermissionId : FORBIDDEN_DELETE_PERMISSION_IDS) {
            if (ids.contains(forbiddenDeletePermissionId)) {
                throw new ServiceException("不能删除系统默认权限");
            }
        }
        if (permissionService.isPermissionCodeUsed(ids)) {
            throw new ServiceException("您删除的权限中存在正在使用的权限，请先解除关联后，再尝试删除");
        }
        return permissionService.removeBatchByIds(ids) ? success("删除成功") : fail("删除失败");
    }
}
